<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频管理 - 视频理解分析工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-secondary {
            background: #f8f9fa;
            color: #495057;
            border: 1px solid #dee2e6;
        }

        .btn-secondary:hover {
            background: #e9ecef;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        .btn-small {
            padding: 8px 16px;
            font-size: 12px;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            border: 1px solid #e9ecef;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #6c757d;
            font-size: 14px;
        }

        .video-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e9ecef;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th,
        .table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        .table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .table td {
            vertical-align: middle;
        }

        .table tbody tr:hover {
            background: #f8f9fa;
        }

        .video-link {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }

        .video-link:hover {
            text-decoration: underline;
        }

        .file-size {
            color: #6c757d;
            font-size: 13px;
        }

        .upload-time {
            color: #6c757d;
            font-size: 13px;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-exists {
            background: #d4edda;
            color: #155724;
        }

        .status-missing {
            background: #f8d7da;
            color: #721c24;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state h3 {
            margin-bottom: 10px;
            color: #495057;
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 30px;
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            text-align: center;
        }

        .modal h3 {
            margin-bottom: 15px;
            color: #495057;
        }

        .modal p {
            margin-bottom: 25px;
            color: #6c757d;
        }

        .modal-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 15px;
            }

            .content {
                padding: 20px;
            }

            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }

            .table-container {
                overflow-x: auto;
            }

            .table {
                min-width: 600px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📹 视频管理</h1>
            <p>管理已上传的视频文件</p>
        </div>

        <div class="content">
            <div class="toolbar">
                <div>
                    <a href="/" class="btn btn-secondary">← 返回首页</a>
                    <a href="/test" class="btn btn-secondary">上传视频</a>
                    <a href="/large-analysis" class="btn btn-secondary">🎞️ 大视频分析</a>
                </div>
                <div>
                    <button onclick="refreshVideoList()" class="btn btn-primary">🔄 刷新列表</button>
                    <button onclick="cleanupOrphanedRecords()" class="btn btn-secondary">🧹 清理记录</button>
                </div>
            </div>

            <div id="alert-container"></div>

            <div class="stats">
                <div class="stat-card">
                    <div class="stat-number" id="total-videos">-</div>
                    <div class="stat-label">总视频数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="total-size">-</div>
                    <div class="stat-label">总大小</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number" id="existing-videos">-</div>
                    <div class="stat-label">有效视频</div>
                </div>
            </div>

            <div class="video-table">
                <div id="loading" class="loading">
                    <p>🔄 加载视频列表中...</p>
                </div>

                <div id="empty-state" class="empty-state" style="display: none;">
                    <h3>📁 暂无视频</h3>
                    <p>还没有上传任何视频文件</p>
                    <a href="/test" class="btn btn-primary">上传第一个视频</a>
                </div>

                <div id="video-list" style="display: none;">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>原文件名</th>
                                <th>文件大小</th>
                                <th>上传时间</th>
                                <th>状态</th>
                                <th>视频链接</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="video-tbody">
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <h3>⚠️ 确认删除</h3>
            <p id="delete-message">确定要删除这个视频文件吗？此操作不可撤销。</p>
            <div class="modal-buttons">
                <button onclick="closeDeleteModal()" class="btn btn-secondary">取消</button>
                <button onclick="confirmDelete()" class="btn btn-danger">删除</button>
            </div>
        </div>
    </div>

    <script>
        let currentDeleteFilename = null;

        // 页面加载时获取视频列表
        document.addEventListener('DOMContentLoaded', function() {
            loadVideoList();
        });

        // 加载视频列表
        async function loadVideoList() {
            try {
                showLoading();
                const response = await fetch('/api/videos');
                const data = await response.json();

                if (data.success) {
                    displayVideoList(data.data);
                    updateStats(data.data);
                } else {
                    showAlert('获取视频列表失败', 'error');
                }
            } catch (error) {
                console.error('Error loading video list:', error);
                showAlert('网络错误，无法加载视频列表', 'error');
            }
        }

        // 显示视频列表
        function displayVideoList(videos) {
            const loading = document.getElementById('loading');
            const emptyState = document.getElementById('empty-state');
            const videoList = document.getElementById('video-list');
            const tbody = document.getElementById('video-tbody');

            loading.style.display = 'none';

            if (videos.length === 0) {
                emptyState.style.display = 'block';
                videoList.style.display = 'none';
                return;
            }

            emptyState.style.display = 'none';
            videoList.style.display = 'block';

            tbody.innerHTML = videos.map(video => `
                <tr>
                    <td>
                        <strong>${escapeHtml(video.original_name)}</strong>
                        <br>
                        <small style="color: #6c757d;">${video.filename}</small>
                    </td>
                    <td>
                        <span class="file-size">${video.file_size_mb} MB</span>
                    </td>
                    <td>
                        <span class="upload-time">${formatDateTime(video.upload_time)}</span>
                    </td>
                    <td>
                        <span class="status-badge ${video.exists ? 'status-exists' : 'status-missing'}">
                            ${video.exists ? '✅ 存在' : '❌ 缺失'}
                        </span>
                    </td>
                    <td>
                        ${video.exists ? 
                            `<a href="${video.video_url}" target="_blank" class="video-link">🔗 查看视频</a>` : 
                            '<span style="color: #6c757d;">不可用</span>'
                        }
                    </td>
                    <td>
                        <button onclick="deleteVideo('${video.filename}', '${escapeHtml(video.original_name)}')" 
                                class="btn btn-danger btn-small">
                            🗑️ 删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 更新统计信息
        function updateStats(videos) {
            const totalVideos = videos.length;
            const existingVideos = videos.filter(v => v.exists).length;
            const totalSize = videos.reduce((sum, v) => sum + v.file_size_mb, 0);

            document.getElementById('total-videos').textContent = totalVideos;
            document.getElementById('existing-videos').textContent = existingVideos;
            document.getElementById('total-size').textContent = totalSize.toFixed(1) + ' MB';
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('empty-state').style.display = 'none';
            document.getElementById('video-list').style.display = 'none';
        }

        // 刷新视频列表
        function refreshVideoList() {
            loadVideoList();
        }

        // 删除视频
        function deleteVideo(filename, originalName) {
            currentDeleteFilename = filename;
            document.getElementById('delete-message').textContent = 
                `确定要删除视频 "${originalName}" 吗？此操作将同时删除视频文件和所有相关的分段文件，不可撤销。`;
            document.getElementById('deleteModal').style.display = 'block';
        }

        // 确认删除
        async function confirmDelete() {
            if (!currentDeleteFilename) return;

            try {
                const response = await fetch(`/api/videos/${currentDeleteFilename}`, {
                    method: 'DELETE'
                });
                const data = await response.json();

                if (data.success) {
                    showAlert('视频删除成功', 'success');
                    loadVideoList(); // 重新加载列表
                } else {
                    showAlert('删除失败: ' + (data.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('Error deleting video:', error);
                showAlert('网络错误，删除失败', 'error');
            }

            closeDeleteModal();
        }

        // 关闭删除模态框
        function closeDeleteModal() {
            document.getElementById('deleteModal').style.display = 'none';
            currentDeleteFilename = null;
        }

        // 清理孤立记录
        async function cleanupOrphanedRecords() {
            try {
                const response = await fetch('/api/videos/cleanup', {
                    method: 'POST'
                });
                const data = await response.json();

                if (data.success) {
                    showAlert(`清理完成，删除了 ${data.cleaned_count} 个孤立记录`, 'success');
                    loadVideoList(); // 重新加载列表
                } else {
                    showAlert('清理失败: ' + (data.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('Error cleaning up records:', error);
                showAlert('网络错误，清理失败', 'error');
            }
        }

        // 显示提示信息
        function showAlert(message, type) {
            const container = document.getElementById('alert-container');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-error';
            
            container.innerHTML = `
                <div class="alert ${alertClass}">
                    ${escapeHtml(message)}
                </div>
            `;

            // 3秒后自动隐藏
            setTimeout(() => {
                container.innerHTML = '';
            }, 3000);
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString || dateString === '未知') return '未知';
            
            try {
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (error) {
                return dateString;
            }
        }

        // HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('deleteModal');
            if (event.target === modal) {
                closeDeleteModal();
            }
        }
    </script>
</body>
</html>